# 智能天气分析Agent - 展示真正的Agent协作能力
import json
import requests
from datetime import datetime, timedelta
from python_a2a import A2AServer, TaskStatus, TaskState, AgentCard, AgentSkill
import os
from openai import OpenAI
import logging

# 配置详细日志记录
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('intelligent_weather_agent.log'),
        logging.StreamHandler()
    ]
)

logger = logging.getLogger('IntelligentWeatherAgent')

class IntelligentWeatherAgent(A2AServer):
    """智能天气分析专家 - 不只查天气，要进行深度分析和协商"""
    
    def __init__(self, agent_card, mcp_url):
        super().__init__(agent_card=agent_card)
        self.mcp_url = mcp_url
        
        # 初始化LLM客户端（用于智能分析）
        deepseek_api_key = os.getenv("DEEPSEEK_API_KEY")
        deepseek_base_url = os.getenv("DEEPSEEK_BASE_URL")
        
        if deepseek_api_key and deepseek_base_url:
            self.llm_client = OpenAI(
                api_key=deepseek_api_key,
                base_url=deepseek_base_url
            )
            self.llm_enabled = True
            print("🧠 LLM分析功能已启用")
        else:
            self.llm_client = None
            self.llm_enabled = False
            print("⚠️ 未配置LLM，将使用基础分析模式")
        
        # 天气专家知识库
        self.weather_expertise = {
            "activity_impact": {
                "museums": {"rain": "positive", "sun": "neutral", "snow": "positive"},
                "outdoor_sightseeing": {"rain": "negative", "sun": "positive", "snow": "mixed"},
                "walking_tours": {"rain": "negative", "sun": "positive", "snow": "negative"},
                "photography": {"rain": "negative", "sun": "positive", "snow": "positive"}
            },
            "crowd_patterns": {
                "rainy_days": "indoor_venues_crowded",
                "sunny_days": "outdoor_venues_crowded", 
                "extreme_weather": "general_low_attendance"
            }
        }
        
        print(f"🌤️ IntelligentWeatherAgent 已启动，具备深度分析和协商能力")

    def handle_task(self, task):
        """处理任务 - 支持多种协作模式"""
        message_data = task.message or {}
        content = message_data.get("content", {})
        text = content.get("text", "")
        
        logger.info(f"🌤️ IntelligentWeatherAgent 收到任务: {text}")
        print(f"🌤️ IntelligentWeatherAgent 收到任务: {text}")
        
        try:
            # 解析请求类型
            if text.startswith('{'):
                request_data = json.loads(text)
            else:
                request_data = {"query": text, "type": "simple_query"}
            
            logger.info(f"📋 解析请求数据: {json.dumps(request_data, ensure_ascii=False, indent=2)}")
            
            # 根据请求类型处理
            if request_data.get("type") == "collaboration_request":
                logger.info("🤝 处理协作请求")
                response = self._handle_collaboration_request(request_data)
            elif request_data.get("type") == "negotiation_request":
                logger.info("⚖️ 处理协商请求")
                response = self._handle_negotiation_request(request_data)
            else:
                logger.info("🔍 处理简单天气查询")
                response = self._handle_simple_weather_query(request_data)
                
        except Exception as e:
            logger.error(f"❌ 处理请求时出错: {str(e)}")
            response = {
                "agent": "IntelligentWeatherAgent",
                "error": f"处理请求时出错: {str(e)}",
                "message": text
            }

        logger.info(f"📤 返回响应: {json.dumps(response, ensure_ascii=False, indent=2)}")
        task.artifacts = [{"parts": [{"type": "text", "text": json.dumps(response, ensure_ascii=False)}]}]
        task.status = TaskStatus(state=TaskState.COMPLETED)
        logger.info("✅ 任务处理完成")
        print(f"🌤️ IntelligentWeatherAgent 完成分析")
        
        # 发送数据流信息到UI（如果有WebSocket连接）
        try:
            import requests
            requests.post("http://localhost:8000/api/notify", json={
                "type": "data_flow",
                "step": {
                    "agent": "IntelligentWeatherAgent",
                    "description": f"天气分析完成 - {request_data.get('type', 'unknown')}",
                    "input": request_data,
                    "output": response,
                    "upstream": "CoordinatorAgent",
                    "downstream": "CoordinatorAgent"
                }
            }, timeout=2)
        except:
            pass  # 忽略UI通知失败
        
        return task

    def _handle_collaboration_request(self, request_data):
        """处理来自其他Agent的协作请求"""
        
        user_requirements = request_data.get("user_requirements", {})
        collaboration_context = request_data.get("collaboration_context", {})
        
        logger.info(f"🤝 开始协作分析: {collaboration_context}")
        logger.info(f"👤 用户需求: {json.dumps(user_requirements, ensure_ascii=False, indent=2)}")
        print(f"🤝 开始协作分析: {collaboration_context}")
        
        # 1. 获取天气数据
        logger.info("📡 获取天气数据")
        location = user_requirements.get("location", "欧洲")
        weather_data = self._get_comprehensive_weather_data(location)
        logger.info(f"🌤️ 天气数据: {json.dumps(weather_data, ensure_ascii=False, indent=2)}")
        
        # 2. 智能分析天气影响
        logger.info("🧠 进行天气影响分析")
        impact_analysis = self._analyze_weather_impact_with_llm(weather_data, user_requirements)
        logger.info(f"📊 影响分析结果: {json.dumps(impact_analysis, ensure_ascii=False, indent=2)}")
        
        # 3. 生成协商建议
        logger.info("💡 生成协商建议")
        negotiation_points = self._generate_negotiation_points(impact_analysis, user_requirements)
        logger.info(f"🤝 协商要点: {json.dumps(negotiation_points, ensure_ascii=False, indent=2)}")
        
        # 4. 预测与其他Agent的潜在冲突
        logger.info("🔮 预测Agent间冲突")
        potential_conflicts = self._predict_inter_agent_conflicts(impact_analysis, user_requirements)
        logger.info(f"⚠️ 潜在冲突: {json.dumps(potential_conflicts, ensure_ascii=False, indent=2)}")
        
        response = {
            "type": "collaboration_response",
            "agent": "IntelligentWeatherAgent",
            "weather_data": weather_data,
            "impact_analysis": impact_analysis,
            "negotiation_points": negotiation_points,
            "potential_conflicts": potential_conflicts,
            "confidence_score": 0.85,
            "collaboration_suggestions": self._suggest_collaboration_strategy(user_requirements)
        }
        
        logger.info("✅ 协作分析完成")
        return response

    def _handle_negotiation_request(self, request_data):
        """处理来自其他Agent的直接协商请求"""
        sender = request_data.get("sender", "Unknown")
        negotiation_context = request_data.get("negotiation_context", {})
        proposals = request_data.get("proposals", [])
        
        logger.info(f"🤝 WeatherAgent收到来自{sender}的协商请求")
        print(f"🤝 WeatherAgent收到来自{sender}的协商请求")
        
        # 分析协商上下文
        issue = negotiation_context.get("issue", "unknown")
        severity = negotiation_context.get("severity", "unknown")
        requested_reduction = negotiation_context.get("requested_cost_reduction", 0)
        
        logger.info(f"📊 协商详情: {issue} (严重程度: {severity}, 请求成本削减: {requested_reduction})")
        
        # 分析每个提案
        proposal_analysis = []
        for proposal in proposals:
            option = proposal.get("option", "")
            description = proposal.get("description", "")
            savings = proposal.get("expected_savings", 0)
            
            # 基于天气专业知识评估提案
            if "adjust_travel_dates" in option:
                analysis = {
                    "proposal": proposal,
                    "weather_feasibility": "high",
                    "weather_impact": "可能获得更好的天气条件",
                    "recommendation": "strongly_support",
                    "confidence": 0.9,
                    "weather_benefits": [
                        "避开恶劣天气期",
                        "减少室内活动成本",
                        "提高户外活动成功率"
                    ]
                }
            elif "increase_indoor_ratio" in option:
                analysis = {
                    "proposal": proposal,
                    "weather_feasibility": "medium",
                    "weather_impact": "减少天气依赖但可能影响体验",
                    "recommendation": "conditional_support",
                    "confidence": 0.7,
                    "weather_benefits": [
                        "降低天气风险",
                        "稳定的活动成本"
                    ],
                    "weather_concerns": [
                        "错过好天气机会",
                        "户外体验减少"
                    ]
                }
            else:
                analysis = {
                    "proposal": proposal,
                    "weather_feasibility": "unknown",
                    "weather_impact": "需要进一步分析",
                    "recommendation": "needs_weather_review",
                    "confidence": 0.5
                }
            
            proposal_analysis.append(analysis)
        
        # 生成WeatherAgent的反建议
        counter_proposals = self._generate_weather_counter_proposals(
            negotiation_context, proposal_analysis
        )
        
        # 选择最佳解决方案
        recommended_solution = self._recommend_weather_solution(
            proposal_analysis, counter_proposals, negotiation_context
        )
        
        response = {
            "type": "negotiation_response",
            "agent": "IntelligentWeatherAgent",
            "sender_ack": sender,
            "negotiation_id": request_data.get("negotiation_id", ""),
            "issue_analysis": {
                "issue": issue,
                "weather_perspective": self._analyze_weather_perspective(issue, negotiation_context),
                "weather_solutions": self._suggest_weather_solutions(issue, requested_reduction)
            },
            "proposal_analysis": proposal_analysis,
            "counter_proposals": counter_proposals,
            "recommended_solution": recommended_solution,
            "negotiation_status": "active",
            "weather_confidence": 0.85,
            "next_steps": [
                "await_budget_agent_response",
                "finalize_weather_adaptation_plan"
            ]
        }
        
        logger.info(f"✅ WeatherAgent协商分析完成，推荐方案: {recommended_solution.get('name', 'unknown')}")
        return response

    def _generate_weather_counter_proposals(self, negotiation_context, proposal_analysis):
        """生成基于天气专业知识的反提案"""
        counter_proposals = []
        
        issue = negotiation_context.get("issue", "")
        severity = negotiation_context.get("severity", "")
        
        if "budget_shortfall" in issue:
            # 天气专家的预算优化建议
            counter_proposals.append({
                "name": "weather_optimal_timing",
                "description": "选择天气最佳的时间段，减少天气应对成本",
                "weather_rationale": "好天气可以节省交通、装备和室内活动费用",
                "estimated_savings": "20-30%的天气相关成本",
                "implementation": [
                    "避开雨季高峰期",
                    "选择温度适宜的月份",
                    "利用天气预报进行微调"
                ]
            })
            
            counter_proposals.append({
                "name": "weather_risk_management",
                "description": "建立天气风险预案，降低意外成本",
                "weather_rationale": "预案可以避免临时应对天气变化的高额费用",
                "estimated_savings": "15-25%的应急成本",
                "implementation": [
                    "准备室内外活动备选方案",
                    "选择天气友好的住宿位置",
                    "预订可取消的活动"
                ]
            })
        
        return counter_proposals

    def _recommend_weather_solution(self, proposal_analysis, counter_proposals, context):
        """推荐基于天气考虑的最佳解决方案"""
        
        # 评估所有方案
        all_options = []
        
        # 评估原始提案
        for analysis in proposal_analysis:
            score = 0
            if analysis.get("recommendation") == "strongly_support":
                score = 9
            elif analysis.get("recommendation") == "conditional_support":
                score = 7
            elif analysis.get("recommendation") == "needs_weather_review":
                score = 5
            
            score += analysis.get("confidence", 0) * 2
            
            all_options.append({
                "type": "original_proposal",
                "data": analysis["proposal"],
                "score": score,
                "weather_reasoning": analysis.get("weather_impact", "")
            })
        
        # 评估反提案
        for counter in counter_proposals:
            score = 8  # 天气专家提案默认较高分
            all_options.append({
                "type": "counter_proposal",
                "data": counter,
                "score": score,
                "weather_reasoning": counter.get("weather_rationale", "")
            })
        
        # 选择最高分方案
        best_option = max(all_options, key=lambda x: x["score"])
        
        return {
            "selected_type": best_option["type"],
            "selected_solution": best_option["data"],
            "weather_confidence": min(best_option["score"] / 10.0, 1.0),
            "weather_reasoning": best_option["weather_reasoning"],
            "implementation_priority": "weather_conditions_first"
        }

    def _analyze_weather_perspective(self, issue, context):
        """从天气角度分析问题"""
        if "budget_shortfall" in issue:
            return {
                "weather_contribution": "恶劣天气通常增加15-25%的旅行成本",
                "primary_factors": [
                    "交通成本增加（出租车代替步行）",
                    "室内活动费用上升",
                    "装备和服装需求",
                    "住宿位置优化成本"
                ],
                "weather_optimization_potential": "通过时间和活动调整可节省20-30%相关成本"
            }
        return {"analysis": "需要更多信息进行天气角度分析"}

    def _suggest_weather_solutions(self, issue, requested_reduction):
        """建议天气解决方案"""
        solutions = []
        
        if "budget_shortfall" in issue:
            solutions.extend([
                {
                    "solution": "date_optimization",
                    "description": "调整旅行日期到天气最佳期",
                    "potential_savings": min(requested_reduction * 0.6, 100)
                },
                {
                    "solution": "activity_weather_matching", 
                    "description": "根据天气预报安排室内外活动",
                    "potential_savings": min(requested_reduction * 0.4, 80)
                },
                {
                    "solution": "location_weather_optimization",
                    "description": "选择天气条件更好的具体地点",
                    "potential_savings": min(requested_reduction * 0.3, 60)
                }
            ])
        
        return solutions

    def _analyze_weather_impact_with_llm(self, weather_data, user_requirements):
        """使用LLM进行深度天气影响分析"""
        
        if not self.llm_enabled:
            logger.info("📊 使用基础分析模式（LLM未配置）")
            print("📊 使用基础分析模式（LLM未配置）")
            return self._basic_weather_analysis(weather_data)
        
        prompt = f"""
作为专业的天气分析师，请分析以下天气对旅行计划的深度影响：

天气数据：
{json.dumps(weather_data, ensure_ascii=False, indent=2)}

用户需求：
{json.dumps(user_requirements, ensure_ascii=False, indent=2)}

请从以下维度进行专业分析：
1. 对不同活动类型的影响程度（博物馆、户外景点、摄影等）
2. 对人群分布的影响（哪些地方会更拥挤）
3. 对交通出行的影响
4. 对服装和装备需求的影响
5. 对整体旅行体验的影响

请以JSON格式返回分析结果，包含具体的数值评分（1-10分）和详细说明。
"""

        logger.info("🧠 调用LLM进行深度分析")
        logger.info(f"📝 LLM提示词: {prompt}")
        
        try:
            response = self.llm_client.chat.completions.create(
                model="deepseek-chat",
                messages=[{"role": "user", "content": prompt}],
                temperature=0.3
            )
            
            analysis_text = response.choices[0].message.content
            logger.info(f"📄 LLM原始响应: {analysis_text}")
            
            # 尝试解析JSON，如果失败则包装成文本
            try:
                parsed_result = json.loads(analysis_text)
                logger.info("✅ LLM分析结果解析成功")
                return parsed_result
            except:
                logger.warning("⚠️ LLM返回的不是有效JSON，使用文本包装")
                return {
                    "analysis_summary": analysis_text,
                    "confidence": 0.8
                }
                
        except Exception as e:
            logger.error(f"⚠️ LLM分析失败，使用基础分析: {str(e)}")
            print(f"⚠️ LLM分析失败，使用基础分析: {str(e)}")
            return self._basic_weather_analysis(weather_data)

    def _generate_negotiation_points(self, impact_analysis, user_requirements):
        """生成与其他Agent的协商要点"""
        
        negotiation_points = []
        
        # 与预算Agent的协商点
        if impact_analysis.get("transportation_impact", {}).get("score", 5) < 6:
            negotiation_points.append({
                "target_agent": "BudgetOptimizer",
                "topic": "transportation_cost_adjustment",
                "proposal": "增加交通预算应对恶劣天气",
                "justification": "恶劣天气需要更多出租车/Uber使用",
                "cost_impact": "+15-25%"
            })
        
        # 与偏好Agent的协商点
        if "outdoor" in user_requirements.get("interests", []):
            negotiation_points.append({
                "target_agent": "PreferenceAnalyzer", 
                "topic": "activity_type_adjustment",
                "proposal": "调整户外活动比例，增加室内替代方案",
                "justification": "天气条件不利于户外活动",
                "satisfaction_impact": "可能降低10-20%户外体验满意度"
            })
        
        # 时间调整建议
        alternative_dates = self._find_better_weather_dates()
        if alternative_dates:
            negotiation_points.append({
                "target_agent": "PlannerAgent",
                "topic": "date_adjustment_option", 
                "proposal": f"调整旅行日期到{alternative_dates['best_date']}",
                "justification": f"天气改善{alternative_dates['improvement']}%",
                "trade_offs": alternative_dates['cost_impact']
            })
        
        return negotiation_points

    def _predict_inter_agent_conflicts(self, impact_analysis, user_requirements):
        """预测与其他Agent可能产生的冲突"""
        
        conflicts = []
        
        # 预测与预算Agent的冲突
        if impact_analysis.get("cost_impact_score", 5) > 7:
            conflicts.append({
                "conflict_type": "budget_vs_weather",
                "severity": "medium",
                "description": "天气条件增加了成本，可能超出预算",
                "affected_agents": ["BudgetOptimizer"],
                "suggested_resolution": "prioritize_weather_adaptation_or_budget_adjustment"
            })
        
        # 预测与偏好Agent的冲突
        user_preferences = user_requirements.get("preferences", {})
        if "outdoor_activities" in user_preferences and impact_analysis.get("outdoor_suitability", 5) < 4:
            conflicts.append({
                "conflict_type": "weather_vs_preference",
                "severity": "high",
                "description": "天气条件与用户户外偏好严重冲突",
                "affected_agents": ["PreferenceAnalyzer"],
                "suggested_resolution": "compromise_with_indoor_alternatives"
            })
        
        return conflicts

    def _suggest_collaboration_strategy(self, user_requirements):
        """建议协作策略"""
        
        return {
            "collaboration_mode": "proactive_negotiation",
            "priority_order": ["user_satisfaction", "safety", "budget_efficiency"],
            "flexibility_areas": ["activity_timing", "indoor_outdoor_balance", "transportation_mode"],
            "non_negotiable": ["safety_standards", "basic_comfort_requirements"]
        }

    def _get_comprehensive_weather_data(self, city):
        """获取全面的天气数据"""
        
        # 城市名称标准化与别名映射
        city_original = city
        city_alias_map = {
            # 中 -> 英 / 其他常见形式
            "北京": "Beijing",
            "beijing": "Beijing",
            "上海": "Shanghai",
            "shanghai": "Shanghai",
            "广州": "Guangzhou",
            "guangzhou": "Guangzhou",
            "深圳": "Shenzhen",
            "shenzhen": "Shenzhen",
            "杭州": "Hangzhou",
            "hangzhou": "Hangzhou",
            "南京": "Nanjing",
            "nanjing": "Nanjing",
            "苏州": "Suzhou",
            "suzhou": "Suzhou",
            "武汉": "Wuhan",
            "wuhan": "Wuhan",
            "西安": "Xi'an",
            "xi'an": "Xi'an",
            "xian": "Xi'an",
            "重庆": "Chongqing",
            "chongqing": "Chongqing",
            "成都": "Chengdu",
            "chengdu": "Chengdu",
            "香港": "Hong Kong",
            "澳门": "Macau",
            "厦门": "Xiamen",
            "青岛": "Qingdao",
            "三亚": "Sanya",
            "汉堡": "Hamburg",
            "hamburg": "Hamburg",
            "慕尼黑": "Munich",
            "慕尼黑市": "Munich",
            "munich": "Munich",
            "法兰克福": "Frankfurt",
            "法兰克福市": "Frankfurt",
            "frankfurt": "Frankfurt",
            "维也纳": "Vienna",
            "vienna": "Vienna",
            "巴黎": "Paris",
            "paris": "Paris",
            "罗马": "Rome",
            "rome": "Rome",
            "米兰": "Milan",
            "milan": "Milan",
            "纽约": "New York",
            "洛杉矶": "Los Angeles",
            "旧金山": "San Francisco",
            "los angeles": "Los Angeles",
            "san francisco": "San Francisco",
            "欧洲": "Europe",
            "europe": "Europe",
            "亚洲": "Asia", 
            "asia": "Asia",
            "美洲": "America",
            "america": "America",
            "非洲": "Africa",
            "africa": "Africa"
        }

        normalized_city = city_alias_map.get(city.strip(), city.strip())
        
        # 特殊处理：如果是大洲名称，选择代表性城市
        continent_representatives = {
            "Europe": "Paris",
            "欧洲": "Paris", 
            "Asia": "Tokyo",
            "亚洲": "Tokyo",
            "America": "New York",
            "美洲": "New York",
            "Africa": "Cairo",
            "非洲": "Cairo"
        }
        
        # 如果是大洲名称，使用代表性城市但保留原始输入信息
        if normalized_city in continent_representatives:
            representative_city = continent_representatives[normalized_city]
            logger.info(f"🌍 检测到大洲查询: {city_original} -> 使用代表性城市: {representative_city}")
        else:
            representative_city = normalized_city

        try:
            # 第一次尝试
            current_weather = self._call_mcp_tool("get_current_weather", {"city": representative_city})

            # 如果返回包含 not found / city not found / 未找到，则尝试回退
            if isinstance(current_weather, str) and any(k in current_weather.lower() for k in ["not found", "city not found", "unknown city"]):
                logger.warning(f"⚠️ 城市第一次查询失败: {current_weather} -> 尝试自动回退策略")

                # 1) 如果原是中文且有映射但失败，尝试直接用英文（已做） -> 尝试小写 / 首字母大写
                fallback_candidates = []
                if normalized_city != city_original:
                    # 已做映射，加入原始城市英文不同格式
                    fallback_candidates.extend([
                        normalized_city.lower(),
                        normalized_city.title(),
                        normalized_city.upper()
                    ])
                else:
                    # 没有映射，尝试首字母大写形式
                    fallback_candidates.extend([
                        city_original.title(),
                        city_original.lower(),
                        city_original.upper()
                    ])

                # 去重
                seen = set()
                fallback_candidates = [c for c in fallback_candidates if not (c in seen or seen.add(c))]

                success = False
                for candidate in fallback_candidates:
                    result = self._call_mcp_tool("get_current_weather", {"city": candidate})
                    if not (isinstance(result, str) and any(k in result.lower() for k in ["not found", "city not found", "unknown city"])):
                        logger.info(f"✅ 通过回退候选 '{candidate}' 获取成功")
                        current_weather = result
                        success = True
                        break

                if not success:
                    # 2) 仍失败，提供模拟数据回退
                    logger.warning(f"⚠️ 所有候选失败，使用模拟天气数据 city={city_original}")
                    current_weather = f"{city_original} 当前天气数据暂不可用(城市识别失败)，使用模拟：多云 18°C，体感 17°C，湿度 60%，微风。"

            # 组装综合数据
            comprehensive_data = {
                "city": city_original,
                "normalized_city": normalized_city,
                "current": self._format_weather_description(current_weather, city_original, representative_city),
                "forecast_3day": self._simulate_forecast(normalized_city),
                "weather_alerts": self._check_weather_alerts(normalized_city),
                "historical_average": self._get_historical_average(normalized_city),
                "uv_index": self._get_uv_index(normalized_city),
                "air_quality": self._get_air_quality(normalized_city),
                "data_source": "mcp_tool_with_fallback" if '模拟' not in str(current_weather) else 'simulated_fallback'
            }

            return comprehensive_data

        except Exception as e:
            logger.error(f"❌ 获取天气数据异常: {e}")
            return {
                "city": city_original,
                "normalized_city": normalized_city,
                "error": f"获取天气数据失败: {str(e)}",
                "current": f"{city_original} 当前天气不可用，使用静态备用：晴 20°C，湿度55%",
                "forecast_3day": self._simulate_forecast(normalized_city),
                "data_source": "exception_fallback"
            }

    def _format_weather_description(self, weather_data, original_city, representative_city):
        """格式化天气描述，特别处理大洲查询"""
        continent_names = {
            "Europe": "欧洲", "欧洲": "欧洲",
            "Asia": "亚洲", "亚洲": "亚洲", 
            "America": "美洲", "美洲": "美洲",
            "Africa": "非洲", "非洲": "非洲"
        }
        
        if original_city in continent_names:
            continent_cn = continent_names[original_city]
            if isinstance(weather_data, str) and representative_city in weather_data:
                # 将代表城市名称替换为大洲名称
                formatted = weather_data.replace(representative_city, f"{continent_cn}(以{representative_city}为代表)")
                return formatted
            else:
                return f"{continent_cn}当前天气（以{representative_city}为代表）: {weather_data}"
        else:
            return weather_data

    def _extract_city_from_query(self, query: str):
        if not query:
            return None
        candidates = [
            "北京","上海","广州","深圳","杭州","南京","苏州","武汉","西安","重庆","成都",
            "汉堡","慕尼黑","慕尼黑市","法兰克福","巴黎","罗马","米兰","三亚","青岛","厦门",
            "欧洲","亚洲","美洲","非洲","大洋洲","欧盟","europe","asia","america","africa"
        ]
        for c in candidates:
            if c in query:
                return c
        # 简单英文匹配
        en_candidates = ["beijing","shanghai","guangzhou","shenzhen","hangzhou","nanjing","suzhou","wuhan","hamburg","munich","frankfurt","paris","rome","milan","europe","asia","america","africa"]
        ql = query.lower()
        for c in en_candidates:
            if c in ql:
                return c
        return None

    def _handle_simple_weather_query(self, request_data):
        """处理最简单的查询（无协作上下文）"""
        city = request_data.get("city") or self._extract_city_from_query(request_data.get("query","")) or "Beijing"
        weather_data = self._get_comprehensive_weather_data(city)
        return {
            "type": "simple_weather_response",
            "agent": "IntelligentWeatherAgent",
            "weather_data": weather_data,
            "summary": weather_data.get("current", "")
        }

    def _call_mcp_tool(self, tool_name, params):
        """调用MCP工具 - 当前使用模拟数据"""
        # 直接使用模拟天气数据，不依赖外部MCP服务
        if tool_name == "get_current_weather" and "city" in params:
            city = params["city"]
            # 返回模拟天气数据
            return f"{city} 当前天气：晴朗 22°C，体感 21°C，湿度 45%，微风。适宜外出活动。"
        return "工具执行成功"

    def _simulate_forecast(self, city):
        """模拟3天天气预报（实际项目中调用真实API）"""
        return [
            {"date": "2025-09-09", "condition": "partly_cloudy", "temp_high": 15, "temp_low": 8, "rain_chance": 30},
            {"date": "2025-09-10", "condition": "rainy", "temp_high": 12, "temp_low": 6, "rain_chance": 80},
            {"date": "2025-09-11", "condition": "sunny", "temp_high": 18, "temp_low": 10, "rain_chance": 10}
        ]

    def _find_better_weather_dates(self):
        """查找更好的天气日期"""
        return {
            "best_date": "2025-09-16",
            "improvement": "40",
            "cost_impact": "酒店价格上涨15%，但整体体验提升"
        }

    def _basic_weather_analysis(self, weather_data):
        """基础天气分析（LLM失败时的后备方案）"""
        return {
            "summary": "基础天气分析",
            "outdoor_suitability": 6,
            "indoor_recommendation": True
        }

    def _check_weather_alerts(self, city):
        """检查天气警报"""
        return {"alerts": [], "severity": "none"}

    def _get_historical_average(self, city):
        """获取历史平均数据"""
        return {"avg_temp": 14, "avg_rain_days": 12}

    def _get_uv_index(self, city):
        """获取UV指数"""
        return {"uv_index": 3, "recommendation": "moderate_protection"}

    def _get_air_quality(self, city):
        """获取空气质量"""
        return {"aqi": 45, "quality": "good"}

if __name__ == "__main__":
    agent_card = AgentCard(
        name="Intelligent Weather Analyst",
        description="智能天气分析专家，具备深度分析和Agent协作能力",
        url="http://localhost:7003",
        version="2.0.0",
        skills=[
            AgentSkill(name="Weather Analysis", description="专业天气数据分析和影响评估"),
            AgentSkill(name="Impact Assessment", description="天气对旅行活动的深度影响分析"),
            AgentSkill(name="Agent Collaboration", description="与其他Agent协商和冲突解决"),
            AgentSkill(name="Negotiation", description="智能协商和替代方案生成"),
            AgentSkill(name="LLM-Enhanced Analysis", description="基于大语言模型的智能分析")
        ]
    )

    weather_agent = IntelligentWeatherAgent(agent_card, "http://localhost:7001")
    print("🌤️ 智能天气分析Agent启动完成")
    
    from python_a2a.server import run_server
    run_server(weather_agent, port=7003)
